#!/usr/bin/python3
#-*- coding=utf-8 -*-

import os
import time
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
from email.header import Header
import subprocess
import tarfile
import shutil
import yaml

CONFIG_FILE = 'oss.yaml'

def send_mail(mail, title, send_str, files, del_file=True):
    sender = mail.get('sender', '')
    receiver = mail.get('receiver', [])
    server = mail.get('SMTP_server', '')
    port = mail.get('SMTP_port', 465)
    password = mail.get('password', '')

    msg = MIMEMultipart()
    msg['Subject'] = Header(title, 'utf-8')
    msg['From'] = 'server<%s>' %sender
    msg['To'] = ';'.join(receiver)
    msg.attach(MIMEText(send_str, 'plain', 'utf-8'))

    #add attachment
    for path in files:
        if not os.path.isfile(path):
            continue
        attachment = MIMEApplication(open(path, 'rb').read())
        attachment.add_header('Content-Disposition', 'attachment', filename='{0}'.format(os.path.basename(path)))
        msg.attach(attachment)
        del_file and os.remove(path)

    try:
        #smtp = smtplib.SMTP()
        #smtp.connect(server)
        smtp = smtplib.SMTP_SSL(server, port)
        smtp.login(sender, password)
        smtp.sendmail(sender, receiver, msg.as_string())
    except Exception as e:
        print("send mail to %s error!" % ";".join(receiver))
        print(e)
    smtp.quit()

def tar(filelist, path_name):
    tf = tarfile.open(path_name, "w:gz")

    for file_name in filelist:
        tf.add(file_name)

    tf.close()

def get_config(file_name):
    """
    解析yaml
    return dict
    """
    if not os.path.exists(file_name):
        return {}

    with open(file_name, "r") as f:
        return yaml.load(f)

def collect_oss_file(dest_dir, oss_file, work_dir):
    if os.path.exists(work_dir):
        shutil.rmtree(work_dir)
        cmd = '''mkdir -p %s''' %work_dir
        status, output= subprocess.getstatusoutput(cmd)
        if status != 0:
            return

    cmd = '''find {0} -name "{1}" | sort | xargs -i{{}} awk -F '|'  '{{print >> "{2}/"$1".txt"}}' {{}}'''.format(dest_dir, oss_file, work_dir)
    status, output= subprocess.getstatusoutput(cmd)
    if status != 0:
        return list()

    return map(lambda file_name: os.path.join(work_dir, file_name), os.listdir(work_dir))

def main():
    config = get_config(os.path.join(os.path.dirname(__file__), CONFIG_FILE))
    setting = config.get('setting', {})
    collector = setting.get('collector', {})

    timestamp = time.time() - 1800
    date = time.strftime("%Y%m%d", time.localtime(timestamp))

    dest_dir = os.path.join(collector.get('dest_dir', './'), date)
    log_path = os.path.join(dest_dir, "*/%s" %collector.get('oss_file', 'world_oss*'))
    work_dir = os.path.join(collector.get('work_dir', './'), date)

    cmd = '''grep "PlayerLogin" %s | awk -F "|" '!a[$7]++{print $7}' | wc -l''' %log_path
    login_count = -1
    status, output= subprocess.getstatusoutput(cmd)
    if status != 0:
        login_count = -1
    else:
        login_count = output

    cmd = '''grep -i "register" %s | awk -F "|" '!a[$7]++{print $7}' | wc -l''' %log_path
    register_count = -1
    status, output= subprocess.getstatusoutput(cmd)
    if status != 0:
        register_count = -1
    else:
        register_count = output
    stay_count = int(login_count) - int(register_count)
    print(login_count, register_count, stay_count, 'asdf')

    files = collect_oss_file(dest_dir, collector.get('oss_file', 'world_oss*'), work_dir)

    file_name = collector.get('result_file', '{}.tar.gz').format(date)
    tar(files, file_name)

    mail = setting.get('mail', {})
    subject = mail.get('subject', '{}')
    content = mail.get('content', '{0} {1} {2}')

    send_mail(mail, subject.format(date), content.format(login_count,register_count, stay_count), [file_name])

if __name__ == "__main__":
    main()
